#include "mysockets.h"
#include "time.h"
#include <stdio.h>

int main(int argc, char ** argv){

	char * host;		//holds the host's name
	char * user;		//holds environment variable
	char * str;		//holds response message to client
	char cmd[20];		//holds the requested command
	char endreq[3];	//holds end of transmission string
	char * timestamp;	//holds timestamps for transmissions
	int port, socket;	//port and socket numbers
	int i, j, exists;	//error checking flags
	int fd, f2, f3;	//file descriptors for the socket and input file
	int dummy;		//dummy int, used for waiting for child to finish
	long bytes;		//number of bytes of incoming file
	FILE * filep;

	int charMX, charMY, charCX, charCY;	// Chars for commands
	int iValue[4];
	char *tString;
	int keepGoing = 1;

	const int bPS = 40, charUsage = 159, numSPC = charUsage/bPS;

	//allocate space for the request response message
	str = (char *) malloc(32*sizeof(char));

	// Temporary string
	tString = (char *) malloc(4*sizeof(char));

	//create an end of transmission string
	endreq[0] = 13;
	endreq[1] = 10;
	endreq[2] = 0;

	//check for correct usage
	if(argc != 3){
		fprintf(stderr, "Usage: ./myserver host port\n");
		exit(1);
	}

	//get the utk netreg name for this pc
	host = argv[1];

	//set the root directory, port, and environment variables
	port = atoi(argv[2]);
	user = getenv("USER");

	//create a socket
	socket = serve_socket(host, port);

	//handle connections
	while(1){
		//fork a child to handle a request
		if(fork() == 0){
			//create a connection
			fprintf(stderr,"Waiting for connection\n");
			fd = accept_connection(socket);

			fprintf(stderr, "Connection established with client\n");

			//read the request
			int i, k = 0, l = 0;

			while(keepGoing == 1){
				fprintf(stderr, "Pre-read\n");
				j=read(fd, str, 1);
				fprintf(stderr, "Post-read\n");
				str[j] = '\0';
				if(j >= 1) {
					i = 0;
					if (((str[i] >= '0') && (str[i] <= '9')) && (k < 3)) {
						tString[k] = str[i];
						k++;
					}
					else if ((k >= 1) && (k < 4)) {
						tString[k] = '\0';
						k = 0;
						if (l < 4) {
							iValue[l] = atoi(tString);
							if (iValue[l] >= 256) {
								keepGoing = 0;
								break;
							}
							l++;
						}
						if (l == 4) {
							l = 0;
							charMX = iValue[0];
							charMY = iValue[1];
							charCX = iValue[2];
							charCY = iValue[3];

							fprintf(stderr, "Data rx:\n");
							fprintf(stderr, "     Robot (%3d, %3d)\n", charMX, charMY);
							fprintf(stderr, "     Camera (%3d, %3d)\n", charCX, charCY);

							// Send movement X command to arduino
							fprintf(stdout, "%c", (char)(charMX/(255/bPS)));

							// Send movement Y command to arduino
							fprintf(stdout, "%c", (char)(charMY/(255/bPS) + bPS));

							// Send camera X command to arduino
							fprintf(stdout, "%c", (char)(charCX/(255/bPS) + 2*bPS));

							// Send camera Y command to arduino
							fprintf(stdout, "%c", (char)(charCY/(255/bPS) + 3*bPS));

							// Flush stdout
							fflush(stdout);

							iValue[l] = atoi(tString);
							if (iValue[l] >= 256) {
								keepGoing = 0;
								break;
							}
						}
					}
				}
			}
			fprintf(stderr, "\nConnection closed\n");
			//terminate child program
			exit(0);

		}
		//have parent wait for processing to finish
		else{
			wait(&dummy);
		} 
	}
	free(host);
	free(str);

}

